package com.liukai.todo_android.presenter;

import android.content.Context;
import android.widget.Toast;

import com.liukai.todo_android.call_back.IAddScheduleCallBack;
import com.liukai.todo_android.common.api.TodoAPI;
import com.liukai.todo_android.common.base.BasePresenter;
import com.liukai.todo_android.common.constants.ScheduleConst;
import com.liukai.todo_android.common.utils.RetrofitManager;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.entity.vo.InsertItemVo;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/16 10:35 上午
 * @description：新增待办的请求
 * @modified By：
 * @version: $
 */
public class AddSchedulePresenter extends BasePresenter<IAddScheduleCallBack> {

    public void addSchedule(InsertItemVo insertItemVo, Context context) {
        if (!validateAdd(insertItemVo, context)) {
            return;
        }
        addSchedule(insertItemVo);
    }

    /**
     * 新增待办
     *
     * @param insertItemVo
     */
    private void addSchedule(InsertItemVo insertItemVo) {


        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        TodoAPI todoAPI = retrofit.create(TodoAPI.class);
        Call<Resp> addScheduleTask = todoAPI.addSchedule(insertItemVo);
        addScheduleTask.enqueue(new Callback<Resp>() {
            @Override
            public void onResponse(Call<Resp> call, Response<Resp> response) {
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    requestSuccess(response);
                } else {
                    requestFailure(response);
                }
            }

            @Override
            public void onFailure(Call<Resp> call, Throwable t) {
                requestFailure(t);
            }
        });
    }

    private boolean validateAdd(InsertItemVo insertItemVo, Context context) {
        if (insertItemVo == null
                || insertItemVo.getUserId() == null
                || insertItemVo.getTitle() == null
                || "".equals(insertItemVo.getTitle())) {
            Toast.makeText(context, "标题不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void requestFailure(Throwable t) {
        mCallBack.addError(Resp.err(ScheduleConst.ADD_SCHEDULE_FAILED_NO_INTERNET));
    }

    private void requestFailure(Response<Resp> response) {
        mCallBack.addError(Resp.err(ScheduleConst.ADD_SCHEDULE_FAILED));
    }

    private void requestSuccess(Response<Resp> response) {
        Resp body = response.body();
        if (body.getCode() == ScheduleConst.ADD_SCHEDULE_SUCCESS.getCode()) {
            mCallBack.addSuccess(body);
            return;
        }
        mCallBack.addError(body);
    }

}
